#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <event.h>
#include "common.h"
#include <errno.h>
#include "http.h"
#include <assert.h>
#include "queue.h"
extern queue q;
extern struct timeval timeout;
int count=0;
int connection=0;
int client_socket(const char *ip,const int port)
{
	int sockfd,ret;
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(set_nonblock(sockfd) < 0)
	{
		close(sockfd);
		return -1;
	}
	struct sockaddr_in server_addr;
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family=AF_INET;
	server_addr.sin_port=htons(port);
	inet_pton(AF_INET,ip,&server_addr.sin_addr);
	ret=connect(sockfd,(struct sockaddr *)&server_addr,sizeof(server_addr));
	return sockfd;

}
void http_write(int sockfd,short event,void *arg)
{
	conn *c=(conn *)arg;
	char buf[1024]={0};
	snprintf(buf,1024,"GET %s HTTP/1.1\r\nHost: 218.30.115.226\r\nConnection: Keep-Alive\r\n\r\n",c->http_url);
	write(sockfd,buf,strlen(buf));
	memset(&(c->ev),0,sizeof(c->ev));
	event_set(&(c->ev),sockfd,EV_READ,http_read,c);
	event_add(&(c->ev),&timeout);
}
void http_read(int sockfd,short event,void *arg)
{
	conn *c=(conn *)arg;
	char *buf=(c->buf)+(c->buf_size);
	int ret;
	char *cl;
	while((ret=read(sockfd,buf,1024)) > 0)
	{
		buf+=ret;
		c->buf_size+=ret;
	}
	if(ret == 0)
	{
		//printf("%s\n",c->buf);
		sendto(c->udp_fd,c->buf,c->buf_size,0,(struct sockaddr *)&(c->client_addr),sizeof(c->client_addr));
		close(sockfd);
		free(c);
	}
	if( ret == -1 )
	{
		if( errno == EAGAIN)
		{
			if( (c->http_len == 0) && (cl=strstr(c->buf,"\r\n\r\n")) != NULL)
			{
				strncpy(c->http_header,c->buf,cl-(c->buf));
				char tbuf[4096]={0};
				strncpy(tbuf,cl+4,4096);
				memset(c->buf,0,sizeof(c->buf));
				strcpy(c->buf,tbuf);
				c->buf_size=strlen(c->buf);
			}
			if( (c->http_len == 0) && (cl=strstr(c->http_header,"Content-Length:")) != NULL)
			{
				cl=strstr(cl," ");
				sscanf(cl,"%d",&(c->http_len));
			}
			if( (c->http_len != 0 ) && (c->http_len == c->buf_size) )
			{
				//printf("%s\n",c->buf);
				sendto(c->udp_fd,c->buf,c->buf_size,0,(struct sockaddr *)&(c->client_addr),sizeof(c->client_addr));
				count++;
				//printf("count: %d\n",count);
				char *cc=strstr(c->http_header,"Connection: close");
				if( cc || queue_add(&q,sockfd) == 0 )
				{
					close(sockfd);
				}
				free(c);
			}
			else
			{
				event_add(&(c->ev),&timeout);
			}
		}
		else
		{
			close(sockfd);
			free(c);
		}
	}
}
/*
int main(int argc,char **argv)
{
	char *ip="218.30.115.226";
	int port=80;
	char *path="/";
	event_init();
	new_http_client();
	event_dispatch();
}
*/
